package myDaos;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.entities.ChubLogNew;
import model.entities.DirListUpdated;



@Stateless
public class LogsDao {
	@PersistenceContext(unitName = "UnileverProcedure")
    private EntityManager em;
	
	public EntityManager getEntityManager() {
        return em;
    }
	
	public List<ChubLogNew> getLogs(){
		List<ChubLogNew> clogs=null;
		try {
			    Query q = getEntityManager().createQuery("SELECT l FROM ChubLogNew l ORDER BY l.issueDate DESC");
			    clogs = q.setMaxResults(50).getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return clogs;
	}
	
	public List<ChubLogNew> getLogsByFilter(String tableName,String msg,Date from,Date to){
		List<ChubLogNew> clogs=null;
		try {
			StringBuffer queryBiffer = new StringBuffer();
			queryBiffer.append(" SELECT l FROM ChubLogNew l WHERE 1=1 "); 
		    	
			if(tableName!=null && !tableName.trim().equals(""))
    	    {
				queryBiffer.append(" and l.tableName = :tableName") ;	
    	    }
			
			if(msg!=null && !msg.trim().equals(""))
    	    {
				queryBiffer.append(" AND l.msg = :msg") ;	
    	    }

			if(from!=null)
    	    {
				queryBiffer.append("  AND l.issueDate >= :fDate") ;	
    	    }

			if(to!=null)
    	    {
				queryBiffer.append("  AND l.issueDate <= :tDate") ;	
    	    }
			
			queryBiffer.append(" ORDER BY l.issueDate DESC ") ;	
			
			
			System.out.println(queryBiffer.toString());
			
			Query q = getEntityManager().createQuery(queryBiffer.toString());

			if(tableName!=null && !tableName.trim().equals("")){q.setParameter("tableName", tableName);} 
			if(msg!=null && !msg.trim().equals("")){q.setParameter("msg", msg);}
			if(from!=null){q.setParameter("fDate", from);}
			if(to!=null){q.setParameter("tDate", to);}
			clogs = q.getResultList();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return clogs;
	}
}
